package com.wcity.manage.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;

/**
 * HTTP 工具类
 * @author chad
 */
public class HttpUtil {
	private static Logger log = Logger.getLogger(HttpUtil.class);
	/**
	 * 默认编码
	 */
	public static final String HTTP_ENCODE = "UTF-8";

	/**
	 * 短信内容编码方式
	 */
	public static final String SMS_ENCODE = "GBK";

	/**
	 * Form 表单参数分隔符
	 */
	public static final String FORM_SEPARATE = "&";

	/**
	 * Form 表单中的赋值标识
	 */
	public static final String FORM_EP = "=";

	/**
	 * POST 请求方式
	 */
	public static final String HTTP_METHOD_POST = "POST";

	/**
	 * GET 请求方式
	 */
	public static final String HTTP_METHOD_GET = "GET";

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<String, String>();

		map.put("name", "123");
		map.put("pass", "123");

		System.out.println(paraToForm(map));
	}
	
	public static String sendPost(String url, String param, String encode){
		return sendPost(url, param, true, encode);
	}
	
	public static String sendPost(String url, Map<String, String> param, String encode){
		return sendPost(url, param, true, encode);
	}
	
	/**
	 * 发送 HTTP POST 请求
	 * @param url		请求的 URL 地址
	 * @param param 	请求的参数内容
	 * @param isForm 	是否是form请求
	 * @param encode 	编码方式，null为默认编码
	 * @return
	 * @throws IOException
	 */
	public static String sendPost(String url, Map<String, String> param, boolean isForm, String encode){
		return sendPost(url, paraToForm(param), isForm, encode);
	}

	/**
	 * 发送 HTTP POST 请求
	 * @param url		请求的 URL 地址
	 * @param param		请求的参数内容
	 * @param isForm	是否是form请求
	 * @param encode	编码方式，null为默认编码
	 * @return
	 * @throws IOException
	 */
	public static String sendPost(String url, String param, boolean isForm,String encode) {
		log.info("Method[sendPost] 请求URL[" + url + "] 参数[" + param + "]");
		StringBuilder result = new StringBuilder();
		try {
			// 打开连接，并设置参数
			URL httpUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
			conn.setDoInput(true); // 设置可输入
			conn.setDoOutput(true);// 设置可输出
			conn.setRequestMethod(HTTP_METHOD_POST);// 设置请求方式为POST
			if (isForm)
				conn.setRequestProperty("Content-type","application/x-www-form-urlencoded;charset=" + encode);
			else
				conn.setRequestProperty("Content-type", "text/html;charset=" + encode);
			conn.connect();

			// 输出
			conn.getOutputStream().write(param.getBytes(encode));
			conn.getOutputStream().flush();
			conn.getOutputStream().close();

			// 输入
			BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), encode));
			String line = null;
			while (null != (line = in.readLine()))
				result.append(line);
			in.close();

			// 关闭连接
			conn.disconnect();
		} catch (IOException e) {
			log.error("Method[sendPost] 网络异常 url[" + url + "]", e);
			throw new RuntimeException(url + " : " +e.getMessage());
		}
		log.info("Method[sendPost] result [" + result.toString() + "]");
		return result.toString();
	}

	/**
	 * 发送 GET 请求
	 * @param url		请求的 URL 地址
	 * @param param		请求的参数
	 * @param encode	请求的编码方式，null为默认编码
	 * @return
	 * @throws IOException
	 */
	public static String sendGet(String url, String encode) {
		log.info("Method[sendPost] 请求URL[" + url + "]");
		StringBuilder result = new StringBuilder();
		try {
			// 打开连接，设置参数
			URL httpUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
			conn.setDoInput(true); // 有返回参数
			conn.setRequestMethod(HTTP_METHOD_GET); // 请求 GET 方式
			conn.setUseCaches(false); // 不使用缓存
			conn.setRequestProperty("Content-type","application/x-www-form-urlencoded"); // 设置 Form 提交方式
			conn.connect();

			String line = null;
			BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), encode));
			while (null != (line = in.readLine()))
				result.append(line);

			// 关闭连接
			conn.getInputStream().close();
			conn.disconnect();
		} catch (IOException e) {
			log.error("Method[sendGet] 网络异常 url[" + url + "]", e);
			throw new RuntimeException(url + " : " + e.getMessage());
		}
		log.info("Method[sendGet] result[" + result.toString() + "]");
		return result.toString();
	}

	/**
	 * 将 map 转化为 Form 形式的参数字符串，如：name=123&pass=123
	 * @param para
	 * @return
	 */
	public static String paraToForm(Map<String, String> para) {
		if (null == para)
			return "";

		StringBuilder result = new StringBuilder();
		for (Iterator<Entry<String, String>> it = para.entrySet().iterator(); it.hasNext();) {
			Entry<String, String> e = it.next();
			result.append(e.getKey()).append("=").append(e.getValue()).append(FORM_SEPARATE);
		}

		if (result.length() > 0)
			result.delete(result.length() - 1, result.length());
		return result.toString();
	}

	/**
	 * 获取参数，使用 {@code getParameter()} 方法
	 * @param reqw
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, String> getParam(HttpServletRequest req) {
		Map<String, String> map = new HashMap<String, String>();
		Enumeration<String> es = req.getParameterNames();

		while (es.hasMoreElements()) {
			String name = es.nextElement();
			String value = req.getParameter(name);

			map.put(name, value);
		}
		return map;
	}

	/**
	 * 获取 POST 参数
	 * 由于使用 MAP 的原因，没有值的参数不获取
	 * @param req
	 * @return
	 * @throws IOException
	 */
	public static Map<String, String> postParam(HttpServletRequest req)
			throws IOException {
		Map<String, String> map = new HashMap<String, String>();

		StringBuilder sb = new StringBuilder();
		String line = null;
		BufferedReader in = new BufferedReader(new InputStreamReader(req.getInputStream()));
		while (null != (line = in.readLine()))
			sb.append(line);

		if (StringUtil.isNull(sb.toString()))
			return map;

		String[] row = sb.toString().split(FORM_SEPARATE);
		for (String r : row) {
			if (StringUtil.isNull(r) || r.length() == r.indexOf(FORM_EP))
				continue;
			map.put(r.substring(0, r.indexOf(FORM_EP)), r.substring(r.indexOf(FORM_EP) + 1));
		}

		return map;
	}

	/**
	 * 解析 URL 中的参数
	 * @return
	 */
	public static Map<String, String> parseURLParam(String strs) {
		Map<String, String> map = new HashMap<String, String>();

		if (StringUtil.isNull(strs))
			return map;

		String str[] = strs.split("&");
		for (String s : str) {
			String[] str2 = s.split("=");
			if (str2 == null || str2.length == 0)
				continue;
			if (str2.length == 1) {
				map.put(str2[0], "");
			} else {
				map.put(str2[0], str2[1]);
			}
		}

		return map;
	}
}